<?php
/**
 * Created by PhpStorm.
 * User: krystal
 * Date: 2019/2/27
 * Time: 10:25
 */

namespace app\api\controller\v9;

use app\api\controller\v2\Auth;
use app\common\cachemodel\ArticleComment;
use app\common\cachemodel\ForbidenRecord;
use app\common\cachemodel\ZlAdminVip;
use app\common\cachemodel\ZlUserNoComment;
use app\common\model\MiddleInformant;
use app\common\model\ZhunleCourseComment;
use app\common\model\ZhunleCourseCommentSupport;
use Exception;
use think\Cache;
use think\Db;
use think\Log;
use think\response\Json;


/**
 * 课程评论相关接口
 * Class CommentForTeach
 * @package app\api\controller\v9
 */
class CommentForTeach extends Auth
{
    /**
     * 课程添加评价相关接口
     * @return Json
     */
    public function save()
    {
        if (!request()->isPost())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $param = request()->param();

        $validate = validate('CommentForTeach');

        //验证请求参数
        if ($validate->scene('save')->check($param) !== true)
        {
            return show(config('code.error'), $validate->getError());
        }

        $id = $param['id'];//课程呢id
        $content = htmlspecialchars(input('param.content'));//评论内容
        $score_for_comment = $param['score_for_comment'];//评论分数
        $uid = $this->user['id'];

        $CourseCommnet = new ZhunleCourseComment();

        $array = [
            'uid' => $uid,
            'cid' => $id,
            'score' => $score_for_comment,
            'content' => $content,
            'create_time' => time()
        ];

        $data = $CourseCommnet->save_data($uid, $id, $array);


        if ($data === false)
        {
            return show(config('code.error'), $CourseCommnet->getError());
        }

        return show(config('code.success'), '添加评论成功');

    }

    /**
     * 课程编辑评价相关接口
     * @return Json
     */
    public function update()
    {
        if (!request()->isPut())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $param = request()->param();

        $validate = validate('CommentForTeach');

        if ($validate->scene('update')->check($param) !== true)
        {
            return show(config('code.error'), $validate->getError());
        }

        $id = $param['video_comment_id'];//评论id
        $score_for_comment = $param['score_for_comment'];//评论分数
        $content = htmlspecialchars(input('param.content'));//评论内容
        $CourseComment = new ZhunleCourseComment();

        $array = [
            'score' => $score_for_comment,
            'content' => $content,
            'update_time' => time()
        ];

        $data = $CourseComment->update_data($id, $array);

        if ($data === false)
        {
            return show(config('code.error'), $CourseComment->getError());
        }

        return show(config('code.success'), '操作成功');


    }

    /**
     * 评价踩或赞相关接口
     * @return Json
     */
    public function support_or_deny()
    {
        if (!request()->isPost())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $param = request()->param();

        $validate = validate('CommentForTeach');

        if ($validate->scene('support_or_deny')->check($param) !== true)
        {
            return show(config('code.error'), $validate->getError());
        }

        $id = $param['video_comment_id'];
        $type = $param['type'];//1=>踩,2=>赞
        $uid = $this->user['id'];

        $CourseCommentSupport = new ZhunleCourseCommentSupport();

        //获取当前评论的踩的用户
        $bad = $CourseCommentSupport->getCourseCommentBadOrGood(['id' => $id, 'type' => 1]);

        //获取当前评论的赞的用户
        $good = $CourseCommentSupport->getCourseCommentBadOrGood(['id' => $id, 'type' => 2]);

        //判断用户是否踩或赞过次评论
        if (in_array($uid, $bad))
        {
            $status = 1;
        } elseif (in_array($uid, $good))
        {
            $status = 2;
        } else
        {
            $status = 0;
        }

        //更新踩或赞的状态
        if ($status && $status != $type)
        {
            $data = $CourseCommentSupport->update_data($uid, $id, $type);

            if ($data === false)
            {
                return show(config('code.error'), $CourseCommentSupport->getError());
            }

            return show(config('code.success'), '操作成功');

        }
        //清除踩或赞的数据
        if ($status && $status == $type)
        {

            $data = $CourseCommentSupport->del_data($uid, $id);

            if ($data === false)
            {
                return show(config('code.error'), $CourseCommentSupport->getError());
            }

            return show(config('code.success'), '操作成功');

        }
        //新增踩或赞的数据
        $data = $CourseCommentSupport->save_data($uid, $id, $type);

        if ($data === false)
        {
            return show(config('code.error'), $CourseCommentSupport->getError());
        }

        return show(config('code.success'), '操作成功');
    }

    /**
     * 评价举报相关接口
     * @return Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws Exception
     */
    public function against_save()
    {
        if (!request()->isPost())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $param = request()->param();

        $validate = validate('CommentForTeach');

        if ($validate->scene('against_save')->check($param) !== true)
        {
            return show(config('code.error'), $validate->getError());
        }

        $comment_id = (int)$param['id'];
        $content = htmlspecialchars($param['content']);
        $type = (int)$param['type'];//[1=>文章评论，2=》视频评价]
        $uid = (int)$this->user['id'];

        $arr = [
            1 => '垃圾营销', // 删除当前评论
            2 => '涉黄信息', // 删除所有评论和回复
            3 => '有害信息', // 删除所有评论和回复禁止评论
            4 => '违法信息', // 删除所有评论和封号
            5 => '侵害人身权益',
            6 => '其他原因'
        ];
        $c_id = array_search($content, $arr) ?? 6;
        $commentModel = new ArticleComment();
        //若是内部vip3进行举报，并且是举报的评论和回复，则进行相关操作
        $vip3 = (new ZlAdminVip())->getVipInfo(3);
        try
        {
            if (in_array($this->user['id'], $vip3) && in_array($c_id, [1, 2, 3, 4], true) && in_array($type, [1, 3], true))
            {
                switch ($c_id)
                {
                    case 1:
                        // 删除当前评论
                        $res = $commentModel->deleteComment($this->user['id'], $comment_id, $c_id, $type);
                        break;
                    case 2: // 删除所有评论和评论回复
                        $res = $commentModel->deleteCommentAll($this->user['id'], $comment_id, $c_id, $type);
                        break;
                    case 3: // 删除所有评论和评论回复并禁止评论
                        $res = $commentModel->deleteCommentAll($this->user['id'], $comment_id, $c_id, $type);
                        if ($res)
                        {
                            // 文章评论禁言
                            $noCommentData = [
                                'uid' => $res,//被禁言的用户
                                'atype' => 1,
                                'aid' => $this->user['id'],
                                'create_time' => time()
                            ];
                            (new ZlUserNoComment())->save($noCommentData);
                            Cache::rm('userinfo:' . $res);
                        }
                        break;
                    case 4: // 删除所有评论和评论回复并封号
                        $res = $commentModel->deleteCommentAll($this->user['id'], $comment_id, $c_id, $type);
                        if ($res)
                        {
                            // 封号
                            (new \app\common\model\User())->save(['forbidden' => 1], ['id' => $res]);
                            //添加封号记录
                            (new ForbidenRecord())->saveData($res, $this->user['id'], $content);
                            Cache::rm('userinfo:' . $res);
                        }
                        break;
                    default :
                        $res = false;
                }
                if ($res)
                {
                    return show(config('code.success'), '操作成功');
                }
                return show(config('code.error'), '操作失败');
            }
        }
        catch (Exception $e)
        {
            Log::write('内部用户 ' . $this->user['id'] . '举报失败：' . $e->getMessage(), 'error');
        }

        switch ($type)
        {
            //文章评论
            case 1:
                $arr = [
                    'comment_id' => $comment_id,
                    'info_id' => $c_id,
                    'uid' => $uid,
                    'create_time' => time(),
                    'type' => 1
                ];
                $res = (new MiddleInformant())->SaveData($arr);
                if ($res === false)
                {
                    return show(config('code.error'), '举报失败');
                }
                break;
            //视频评论
            case 2:
                $array = [
                    'uid' => $uid,
                    'cid' => $comment_id,
                    'content' => $c_id,
                    'create_time' => time()
                ];

                try
                {
                    Db::table('wechat_backup_07_18_14_43_00.zhunle_course_comment_complain')->insertGetId($array);
                }
                catch (Exception $e)
                {
                    return show(config('code.error'), '举报成功');
                }
                break;
        }

        return show(config('code.success'), '举报成功');
    }
}
